import asyncio
import threading
import sys
import os
from typing import List
import time
from PyQt5.QtWidgets import QApplication,QWidget,QVBoxLayout,QPushButton


def create_event_loop_thread(worker,ips:List[str],*args,**kwargs):
    """
    创建一个拥有自己事件循环的线程
    :param worker: 线程执行函数
    :param ips:
    :param args:
    :param kwargs:
    :return:
    """
    def _worker(*args,**kwargs):
        loop = asyncio.new_event_loop()
        try:
            asyncio.set_event_loop(loop)

            async def run_tasks():
                tasks = [asyncio.create_task(worker(ip,*args,**kwargs)) for ip in ips ]

                # wait 和 gather 的区别
                await asyncio.wait(tasks)
                #await asyncio.gather(*tasks)
            asyncio.run(run_tasks())
        finally:
            loop.close()
    return threading.Thread(target=_worker,args=args,kwargs=kwargs)


async def download_file(*args,**kwargs):
    print(f"In 线程-{threading.get_ident()}",args,kwargs,id(asyncio.get_event_loop()))
    await asyncio.sleep(4)
    print(f"线程-{threading.get_ident()}结束")

def main_console():
    t = create_event_loop_thread(download_file,["10.200.10.1","10.200.10.2"],"20210601")
    t.setDaemon(True)
    t.start()
    #t.join()
    while t.is_alive():
        print('t is alive ')
        time.sleep(1)
    print("over")


class View(QWidget):
    def __init__(self,*args,**kwargs):
        super(View, self).__init__(*args,**kwargs)
        self.init_ui()

    def init_ui(self):
        self.setGeometry(100,200,600,400)
        box = QVBoxLayout()
        self.setLayout(box)
        btn = QPushButton("OK")
        box.addWidget(btn)
        btn.clicked.connect(self.run)
        self.show()
    def get_text(self):
        return "AAAA"
    def get_date(self):
        return "20210506"
    def callback(self,*args,**kwargs):
        print(*args,**kwargs)

    def run(self):
        t = create_event_loop_thread(download_file, ["10.200.10.1", "10.200.10.2","10.200.10.3"], "20210601")
        t.setDaemon(True)
        t.start()
        # t.join()
        # while t.is_alive():
        #     print('t is alive ')
        #     time.sleep(1)
        # print("over")

def main_qt():
    # View().run()
    app = QApplication(sys.argv)
    # QWidget部件是pyqt5所有用户界面对象的基类。他为QWidget提供默认构造函数。默认构造函数没有父类。
    view = View()

    # 系统exit()方法确保应用程序干净的退出
    # 的exec_()方法有下划线。因为执行是一个Python关键词。因此，exec_()代替
    sys.exit(app.exec_())

if __name__ == '__main__':
    main_console()